import axios from 'axios'
import { Message } from 'element-ui'

const instance = axios.create({
  // TODO: 记得改地址
  // baseURL: 'http://video.johnxu.net/index.php/admin'
  baseURL: 'http://localhost:8000/admin'
})

instance.interceptors.request.use(config => {
  const token = sessionStorage.getItem('token')
  if (token) { config.headers.Authorization = sessionStorage.getItem('token') }
  return config
})

instance.interceptors.response.use(response => {
  // 拦截返回码不是 200
  if ([401, 403].includes(response.data.code)) {
    // 清除本地的 token
    sessionStorage.removeItem('token')
    window.location.href = '/'
    return Promise.reject(response.data)
  }
  if (response.data.code !== 200) {
    Message.error(response.data.message)
    return Promise.reject(response.data)
  }
  return response.data
}, error => {
  Message.error(error.response.data)
  return Promise.reject(error.response.data)
})

export default instance
